package com.haoran.dwz.service.impl;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;

import com.haoran.dwz.dto.DwzGeneratorDTO;
import com.haoran.dwz.rest.R;
import com.haoran.dwz.security.AuthenticationHeader;
import com.haoran.dwz.service.DwzService;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class DwzServiceOkHttpImpl implements DwzService {

	@Autowired
	private OkHttpClient okHttpClient;

	@Autowired
	private AuthenticationHeader authenticationHeader;

	@Value("${dwz.service.address:https://localhost:8443/}")
	private String SERVICE_ADDRESS;
 
	@Override
	public ResponseEntity<R> generate(String url, int type) {
		try {
			DwzGeneratorDTO params = new DwzGeneratorDTO(url, type);
			String content = com.alibaba.fastjson.JSONObject.toJSONString(params);
			String serviceUrl = SERVICE_ADDRESS + DWZ_GENERATE;
			RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), content);
			Builder requestBuilder = new Request.Builder().url(serviceUrl).post(body);
			Map<String, String> headers = authenticationHeader.create(content);
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				requestBuilder.addHeader(entry.getKey(), entry.getValue());
			}
			Request request = requestBuilder.build();
			Response execute = okHttpClient.newCall(request).execute();
			if (execute.isSuccessful()) {
				String responseBody = execute.body().string();
				return ResponseEntity.ok(com.alibaba.fastjson.JSONObject.parseObject(responseBody, R.class));
			} else {
				return ResponseEntity.badRequest().build();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return ResponseEntity.badRequest().build();
		}
	}
}
